package dk.aau.walkietalkie.database;

import java.util.ArrayList;

import android.util.Log;

import dk.aau.walkietalkie.network.UDPBroadcastSender;
import dk.aau.walkietalkie.network.NetworkHelper;
import dk.aau.walkietalkieui.IDBUpdateNotifier;
import dk.aau.walkietalkieui.WalkieTalkieApplication;

public class DataEntriesAliveCounter implements Runnable {

	public static int TIMEOUT_PENDING = 3;
	public static int TIMEOUT_OFFLINE = 5;
	public static int TIMEOUT_INTERVAL = UDPBroadcastSender.BROADCAST_INTERVAL; // ms
	private static String DEBUG_TAG = "DataEntriesAliveCounter";
	
	private IDBUpdateNotifier contactListUpdater;
	private boolean stopAliveCounter;
	
	public DataEntriesAliveCounter(IDBUpdateNotifier updater) {
		this.contactListUpdater = updater;
	}

	public void stopAliveCounter() {
		stopAliveCounter = true;
	}
	
	public void setUpdater(IDBUpdateNotifier updater) {
		contactListUpdater = updater;
	}

	@Override
	public void run() {
		stopAliveCounter = false;

		while (!stopAliveCounter) {
			DBController controller = new DBController(WalkieTalkieApplication.getContext());
			ArrayList<Identification> contactList = controller.getAllContacts();

			for (Identification contact : contactList) {
				// increase the alive counter for all contacts
				contact.setAliveCounter(contact.getAliveCounter() + 1);
				Log.v(DEBUG_TAG, "incrementing alive ctr of " + contact.getIp()
						+ " to " + contact.getAliveCounter());
				
				if (contact.getAliveCounter() >= TIMEOUT_OFFLINE
						&& (!UDPBroadcastSender.GENERIC_BROADCAST_ADDRESS
								.equals(contact.getIp()))) {
					controller.deleteRow(contact.getIp());
					Log.d(DEBUG_TAG, "Deleting " + contact.getIp() + " from contact list.");
					// Update contact list through interface after the change
					contactListUpdater.UpdateUI();
				} else {
					// Just increase the row counter
					controller.updateRow(contact);
					Log.v(DEBUG_TAG, "Updating contact table entry of " + contact.getIp());
				}
			}

			if (controller != null) {
				controller.close();
			}
			try {
				Thread.sleep(TIMEOUT_INTERVAL);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}

	}

}
